package com.glory.dgcpcpda.activity.mfg;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.adapter.EqpKeepCheckListAdapter;
import com.glory.dgcpcpda.adapter.EqpKeepInputListAdapter;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.base.Constant;
import com.glory.dgcpcpda.entity.EqpKeepBean;
import com.glory.dgcpcpda.entity.EqpKeepInputListBean;
import com.glory.dgcpcpda.entity.EqpKeepSelectorListBean;
import com.glory.dgcpcpda.entity.MesReturnEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

public class Eqp_EqpKeepDetailsActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener {

    @BindView(R.id.etaffirmant)
    FreeUI_ClearEditText etaffirmant;
    @BindView(R.id.rvKeepCheckList)
    RecyclerView rvKeepCheckList;
    @BindView(R.id.rvKeepInputList)
    RecyclerView rvKeepInputList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvReplay)
    TextView tvReplay;
    @BindView(R.id.tvReplay_QC)
    TextView tvReplay_QC;
    @BindView(R.id.llCheckLayout)
    LinearLayout llCheckLayout;
    @BindView(R.id.llInputLayout)
    LinearLayout llInputLayout;
    @BindView(R.id.tvSave)
    TextView tvSave;
    @BindView(R.id.tvDataEcq)
    TextView tvDataEcq;
    private String scheduleRrn;
    private EqpKeepCheckListAdapter eqpKeepCheckListAdapter;
    private EqpKeepInputListAdapter eqpKeepInputListAdapter;
    private List<EqpKeepSelectorListBean> checkTableLineDatas;
    private String eqpWork;
    private String sheetName;


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_eqp_keep_detials;
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        scheduleRrn = bundle.getString("scheduleRrn");
        eqpWork = bundle.getString("eqpWork");
        sheetName = bundle.getString("sheetName");
        int jumpType = bundle.getInt("jumpType", -1);
        if (jumpType == 1){
            freeUI_titleView.setTitle("治具保养");
            tvReplay_QC.setVisibility(View.GONE);
        }else {
            freeUI_titleView.setTitle("设备保养");
            tvReplay_QC.setVisibility(View.VISIBLE);
        }

        rvKeepCheckList.setLayoutManager(new LinearLayoutManager(Eqp_EqpKeepDetailsActivity.this));
        rvKeepCheckList.setItemAnimator(new DefaultItemAnimator());
        rvKeepCheckList.addItemDecoration(new DividerItemDecoration(Eqp_EqpKeepDetailsActivity.this, 1));
        eqpKeepCheckListAdapter = new EqpKeepCheckListAdapter(null,true);
        eqpKeepCheckListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        eqpKeepCheckListAdapter.isFirstOnly(true);
        rvKeepCheckList.setAdapter(eqpKeepCheckListAdapter);

        rvKeepInputList.setLayoutManager(new LinearLayoutManager(Eqp_EqpKeepDetailsActivity.this));
        rvKeepInputList.setItemAnimator(new DefaultItemAnimator());
        rvKeepInputList.addItemDecoration(new DividerItemDecoration(Eqp_EqpKeepDetailsActivity.this, 1));
        eqpKeepInputListAdapter = new EqpKeepInputListAdapter(null,true);
        eqpKeepInputListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        eqpKeepInputListAdapter.isFirstOnly(true);
        rvKeepInputList.setAdapter(eqpKeepInputListAdapter);

        eqpKeepCheckListAdapter.setOnItemClickListener(this);

        tvDataEcq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Bundle bundle = new Bundle();
                bundle.putString("sheetName", sheetName);

                FreeApi_Utils.skipWithExtraIntent("header", bundle, Eqp_EqpKeepDetailsActivity.this, Eqp_DataAcquisitionActivity.class);
            }
        });
    }



    @Override
    protected void initData() {

        FreeUI_EntityCallBack<BaseResponseBean<EqpKeepBean>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<EqpKeepBean>>
                (new TypeToken<BaseResponseBean<EqpKeepBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<EqpKeepBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    EqpKeepBean eqpKeepBean = response.body().getResponse().getBody();
                    if (eqpKeepBean.getCheckTableLineDatas().size() > 0) {
                        llCheckLayout.setVisibility(View.VISIBLE);
                        checkTableLineDatas = eqpKeepBean.getCheckTableLineDatas();
                        eqpKeepCheckListAdapter.setNewData(checkTableLineDatas);
                    }

                    if (eqpKeepBean.getLineDatas().size() > 0) {
                        llInputLayout.setVisibility(View.VISIBLE);
                        eqpKeepInputListAdapter.setNewData(eqpKeepBean.getLineDatas());
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<EqpKeepBean>> response) {
                super.onError(response);
                loadError(response.getException(), "PMSSCHEDULE");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("actionType", "queryScheduleForm");
        map.addProperty("scheduleRrn", scheduleRrn);
        NetUtils.requestPostNet("CPC.PMSSCHEDULE", "PMSSCHEDULE", this, map, callBack);

    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setRightListener(R.drawable.selector_refresh, v -> {
            eqpKeepCheckListAdapter.getData().clear();
            eqpKeepCheckListAdapter.notifyDataSetChanged();
            eqpKeepInputListAdapter.getData().clear();
            eqpKeepInputListAdapter.notifyDataSetChanged();
            eqpKeepInputListAdapter.clearData();
            initData();
        });
        return new FreeUI_AddViewEntity("header", llMain);
    }

    @OnClick({R.id.tvReplay, R.id.tvSave, R.id.tvReplay_QC})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvSave:
                showSubmitDialog(new onSubmitListener() {
                    @Override
                    public void setOnSubmitListener() {
                        submit("false","");
                    }
                },"临时保存确认？");
                break;
            case R.id.tvReplay:
                if(getText(etaffirmant).equals(Constant.CURRENT_USER)){
                    showConfirmDialog("确认人和登陆人不能一致");
                    return;
                }
                if(getText(etaffirmant).equals("")||getText(etaffirmant).equals(null)){
                    showConfirmDialog("确认人不能为空");
                    return;
                }
                showSubmitDialog(new onSubmitListener() {
                    String tvReplayisFinished="true";
                    @Override
                    public void setOnSubmitListener() {
//                        if (eqpKeepInputListAdapter.getOutData().size() > 0) {
//                            showConfirmDialog("数值已超限");
//                            return;
//                        }
                        List<EqpKeepInputListBean> dataline = eqpKeepInputListAdapter.getData();
                        for (EqpKeepInputListBean bean : dataline) {
                            if(Float.parseFloat(bean.getMinValue())>Float.parseFloat(bean.getDataString())||Float.parseFloat(bean.getMaxValue())<Float.parseFloat(bean.getDataString())){
                                tvReplayisFinished="false";
                            }
                        }

                        List<EqpKeepSelectorListBean> data = eqpKeepCheckListAdapter.getData();
                        for (EqpKeepSelectorListBean bean : data) {
                            if (FreeApi_StringUtils.isEmpty(bean.getReserved1())) {
                                showToast("保养状态项不能为空", false);
                                return;
                            }
                            if(bean.getReserved1().equals("N")){
                                tvReplayisFinished="false";
                            }

//                            if (FreeApi_StringUtils.isEmpty(bean.getReserved9()) && bean.getReserved10().length() > 0 && !bean.getReserved10().contains(";")) {
//                                showToast("QC采集项未完成", false);
//                                return;
//                            }
                        }
                        submit(tvReplayisFinished,"");
                    }
                },"确认提交？");
                break;
            case R.id.tvReplay_QC:
                showSubmitDialog(new onSubmitListener() {

                    String tvReplayisFinished="true";
                    @Override
                    public void setOnSubmitListener() {
                        if (eqpKeepInputListAdapter.getOutData().size() > 0) {
                            showConfirmDialog("数值已超限");
                            return;
                        }
                        List<EqpKeepInputListBean> dataline = eqpKeepInputListAdapter.getData();
                        for (EqpKeepInputListBean bean : dataline) {
                            if(Float.parseFloat(bean.getMinValue())>Float.parseFloat(bean.getDataString())||Float.parseFloat(bean.getMaxValue())<Float.parseFloat(bean.getDataString())){
                                tvReplayisFinished="false";
                            }
                        }
                        List<EqpKeepSelectorListBean> data = eqpKeepCheckListAdapter.getData();
                        for (EqpKeepSelectorListBean bean : data) {
                            if (FreeApi_StringUtils.isEmpty(bean.getReserved1())) {
                                showToast("保养状态项不能为空", false);
                                return;
                            }
                            if(bean.getReserved1().equals("N")){
                                tvReplayisFinished="false";
                            }
//                            if (FreeApi_StringUtils.isEmpty(bean.getReserved9()) && bean.getReserved10().length() > 0 && !bean.getReserved10().contains(";")) {
//                                showToast("QC采集项未完成", false);
//                                return;
//                            }
                        }
                        submit(tvReplayisFinished,"QC");
                    }
                },"确认提交？");
                break;
        }
    }

    private void submit(String isFinished,String qc) {

        FreeUI_EntityCallBack<BaseResponseBean<MesReturnEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<MesReturnEntity>>
                (new TypeToken<BaseResponseBean<MesReturnEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<MesReturnEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                    if(response.body().getResponse().getBody().getFLAGNG().equals("NG")){
                        showConfirmDialog(Eqp_EqpKeepDetailsActivity.this, response.body().getResponse().getBody().getCOMMENT());
                    }else{
                        showConfirmDialog(Eqp_EqpKeepDetailsActivity.this, "操作成功");
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<MesReturnEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "PMSSCHEDULE");
            }
        };

        JsonObject map = new JsonObject();
//        JsonObject checkJson = new JsonObject();
//        checkJson.add("XPdaPmsSheetCheckTableLineData", new JsonParser().parse(new Gson().toJson(eqpKeepCheckListAdapter.getData())).getAsJsonArray());
//        JsonObject inputJson = new JsonObject();
//        inputJson.add("XPdaPmsDatasLineData", new JsonParser().parse(new Gson().toJson(eqpKeepInputListAdapter.getData())).getAsJsonArray());
        map.addProperty("actionType", "saveScheduleForm");
        map.addProperty("isFinished", isFinished);
        map.addProperty("reserved8", getText(etaffirmant));//确认人字段
        map.addProperty("QC",qc.equals("")?"":"PM_QC");
        map.add("XPdaPmsDatasLineDatas", new JsonParser().parse(new Gson().toJson(eqpKeepInputListAdapter.getData())).getAsJsonArray());
        map.add("XPdaPmsSheetCheckTableLineDatas", new JsonParser().parse(new Gson().toJson(eqpKeepCheckListAdapter.getData())));
        map.addProperty("scheduleRrn", scheduleRrn);
        NetUtils.requestPostNet("CPC.PMSSCHEDULE", "PMSSCHEDULE", this, map, callBack);

    }


    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        EqpKeepSelectorListBean item = checkTableLineDatas.get(position);
//        if (item.getReserved10().length() > 0 && !item.getReserved10().contains(";") && !item.getReserved9().equals("Y")) {
//            if (actionControl("Work_DataCollectActivity", "PDAWorkFragment", "无一般数据采集权限")) {
//                return;
//            }
//            Intent intent = new Intent(this, Work_DataCollectActivity.class);
//            intent.putExtra("position", String.valueOf(position));
//            intent.putExtra("eqpWork", eqpWork);
//            intent.putExtra("paramList", item.getReserved10());
//            startActivityForResult(intent, 500);
//        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 500) {
                if (data != null) {
                    int position = Integer.parseInt(data.getStringExtra("position"));
                    if (position >= 0) {
                        checkTableLineDatas.get(position).setReserved9("Y");
                        eqpKeepCheckListAdapter.notifyItemChanged(position);
                    } else {
                        showConfirmDialog("数据采集填写错误");
                    }

                }
            }
        }
    }
}
